package com.bee.admin.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.social.UserIdSource;
import org.springframework.social.config.annotation.ConnectionFactoryConfigurer;
import org.springframework.social.config.annotation.EnableSocial;
import org.springframework.social.config.annotation.SocialConfigurerAdapter;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.jdbc.JdbcUsersConnectionRepository;
import org.springframework.social.connect.web.ConnectController;
import org.springframework.social.connect.web.ProviderSignInUtils;

import com.bee.admin.social.qq.connect.QQAdapter;
import com.bee.admin.social.qq.connect.QQConnectionFactory;
import com.bee.admin.social.qq.connect.QQServiceProvider;

@Configuration
@EnableSocial
public class SocialConfig extends SocialConfigurerAdapter{
	
	@Autowired
	private DataSource dataSource;
	
	@Override
	public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
		// TODO Auto-generated method stub
		return new JdbcUsersConnectionRepository(dataSource, connectionFactoryLocator, Encryptors.noOpText());
	}
	
	@Override
	public void addConnectionFactories(ConnectionFactoryConfigurer connectionFactoryConfigurer,
			Environment environment) {
		connectionFactoryConfigurer.addConnectionFactory(new QQConnectionFactory("qq",
				new QQServiceProvider("101386962", "2a0f820407df400b84a854d054be8b6a"), new QQAdapter()));
	}
	
	@Bean
	public QQSpringSocialConfigure QQSpringSocialConfigure() {
		return new QQSpringSocialConfigure("/login");
	}
	
	
	 @Bean
    public ProviderSignInUtils providerSignInUtils(ConnectionFactoryLocator factoryLocator) {
        return new ProviderSignInUtils(factoryLocator, getUsersConnectionRepository(factoryLocator));
    }
	
	@Override
	public UserIdSource getUserIdSource() {
		// TODO Auto-generated method stub
		return new UserIdSource() {
			
			@Override
			public String getUserId() {
				return null;
			}
		};
	}
	
	
	@Bean
	public ConnectController connectController(ConnectionFactoryLocator connectionFactoryLocator,
	                                           ConnectionRepository connectionRepository) {
	    ConnectController controller = new ConnectController(connectionFactoryLocator, connectionRepository);
	   // controller.setApplicationUrl();
	    return controller;
	}
}	
